package com.doctcloud.datacloud.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api")
public class ZipController {

    private static final String ZIP_FILE_PATH = "d:/zip/2024-05-20_encrypted.zip";

    /**
     * 下载服务器上指定的ZIP文件
     *
     * @param response HttpServletResponse 对象，用于构建响应
     */
    @PostMapping("/export")
    public void exportZip(HttpServletResponse response) {
        System.out.println("下载开始");
        File zipFile = new File(ZIP_FILE_PATH);

        // 1. 检查文件是否存在
        if (!zipFile.exists() || !zipFile.canRead()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            try (PrintWriter writer = response.getWriter()) {
                writer.write("文件未找到或无法读取: " + ZIP_FILE_PATH);
            } catch (IOException e) {
                // 记录日志
                e.printStackTrace();
            }
            return;
        }

        try {
            // 2. 设置响应头，通知浏览器以附件形式下载
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String fileName = URLEncoder.encode(zipFile.getName(), StandardCharsets.UTF_8.toString());
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
            response.setContentLengthLong(zipFile.length());

            // 3. 准备文件输入流和响应输出流
            try (InputStream in = new FileInputStream(zipFile);
                 OutputStream out = response.getOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                // 4. 循环读取文件内容并写入响应流
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                // 5. 刷新输出流，确保所有数据都已发送
                out.flush();
            }
        } catch (IOException e) {
            // 记录日志
            e.printStackTrace();
            // 向客户端反馈错误
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try (PrintWriter writer = response.getWriter()) {
                writer.write("文件下载失败: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
